package com.zbkj.front.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.community.CommunityTopic;
import com.zbkj.common.request.CommunityTopicSaveRequest;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.result.CommunityResultCode;
import com.zbkj.front.service.FrontCommunityTopicService;
import com.zbkj.service.dao.community.CommunityTopicDao;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * CommunityTopic 接口实现
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Service
public class FrontCommunityTopicServiceImpl extends ServiceImpl<CommunityTopicDao, CommunityTopic> implements FrontCommunityTopicService {


    @Autowired
    private CommunityTopicDao dao;

    /**
     * 添加社区话题
     */
    @Override
    public void add(CommunityTopicSaveRequest request) {
        if (isExistName(request.getName(), 0)) {
            throw new CrmebException(CommunityResultCode.COMMUNITY_TOPIC_NAME_EXIST);
        }
        CommunityTopic topic = new CommunityTopic();
        BeanUtils.copyProperties(request, topic, "id");
        topic.setIsHot(0);
        boolean save = save(topic);
        if (!save) {
            throw new CrmebException(CommonResultCode.ERROR.setMessage("添加社区话题失败"));
        }
    }

    private boolean isExistName(String name, Integer id) {
        LambdaQueryWrapper<CommunityTopic> lqw = Wrappers.lambdaQuery();
        lqw.select(CommunityTopic::getId);
        lqw.eq(CommunityTopic::getName, name);
        lqw.eq(CommunityTopic::getIsDel, 0);
        if (ObjectUtil.isNotNull(id) && id > 0) {
            lqw.ne(CommunityTopic::getId, id);
        }
        lqw.last(" limit 1");
        CommunityTopic communityTopic = dao.selectOne(lqw);
        return ObjectUtil.isNotNull(communityTopic);
    }

}

